#!/usr/bin/python3
# encoding: utf-8
# description: program upgrade

import logging
import os
import shutil


try:
    import jkzuc

    JKROOT_DIR = jkzuc.jkroot_dir
except:
    JKROOT_DIR = "/usr/etc/jkzuc/"


# 安装包解压后路径
_INSTALL_PATH = os.path.join(JKROOT_DIR, "scripts/jkzuc/")

# jaka upgrade loader 执行日志，会在诊断时被导出
_JKZUC_UPGRADE_LOG_PATH = os.path.join(JKROOT_DIR, "scripts/log/jaka_upgrade.log")


class RetCode:
    RET_SUCC = 0
    RET_FAIL = 1


# def get_dir_size(dir_path):
#     '''
#         获取目录大小， 单位 B
#     '''
#     total_size = 0
#     for dirpath, _dirnames, filenames in os.walk(dir_path):
#         for f in filenames:
#             fp = os.path.join(dirpath, f)
#             if not os.path.islink(fp):  # 排除符号链接
#                 total_size += os.path.getsize(fp)
#     return total_size


# def get_pation_free_size(dir_path):
#     '''
#         获取分区剩余大小， 单位 B
#     '''
#     _total, _used, free = shutil.disk_usage(dir_path)
#     return free


def find_install_root_dirs():
    # 控制器安装包目录被解压在 _INSTALL_PATH目录下，确认解压后的目录存在
    sub_dirs = os.listdir(_INSTALL_PATH)

    # 过滤出所有的目录
    sub_dirs = [dirname for dirname in sub_dirs if os.path.isdir(os.path.join(_INSTALL_PATH, dirname))]

    if len(sub_dirs) <= 0:
        return None

    # 按ascii码序排序
    sub_dirs = sorted(sub_dirs)    
    install_root_dirs = sub_dirs
    return install_root_dirs


def find_first_make_install_root_dir(dirlist):
    '''
        dirlist _INSTALL_PATH 下的有序数组
    '''
    mkroot_dir = None
    for dirname in dirlist:
        mkfile_path = os.path.join(_INSTALL_PATH, dirname, 'Install', 'Makefile')
        if os.path.isfile(mkfile_path):
            mkroot_dir = dirname
            break
    return mkroot_dir


def run_upgrade_loader():
    # 检查安装目录是否存在, 不存在则直接退出
    if not os.path.exists(_INSTALL_PATH):
        return RetCode.RET_SUCC

    install_root_dirs = find_install_root_dirs()
    if install_root_dirs is None:
        logger.error('no installation directory could be found.')
        shutil.rmtree(_INSTALL_PATH, ignore_errors=True)
        return RetCode.RET_FAIL

    # 检查新的包结构, 是否存在 jaka_upgrade.py文件
    # JAKA_UPGRADE_PYC_DIR = os.path.join(_INSTALL_PATH, upgrade_package, 'Install')
    # JAKA_UPGRADE_PYC_PATH = os.path.join(JAKA_UPGRADE_PYC_DIR, 'jaka_upgrade.py')
    # if os.path.exists(JAKA_UPGRADE_PYC_PATH):
    #     # 支持通过jaka_upgrade.py的方式安装, 移交控制权到包内的jaka_upgrade脚本
    #     # os.execl 不会返回，使用bash -c 替换当前进程，保留pid
    #     os.execl('/usr/bin/bash', 'bash', '-c', f'cd {JAKA_UPGRADE_PYC_DIR} && /usr/bin/python3 jaka_upgrade.py')

    mkinst_root_dir = find_first_make_install_root_dir(install_root_dirs)
    if mkinst_root_dir is not None:
        JAKA_UPGRADE_MKFILE_DIR = os.path.join(_INSTALL_PATH, mkinst_root_dir, 'Install')
        JAKA_UPGRADE_MKFILE_PATH = os.path.join(_INSTALL_PATH, mkinst_root_dir, 'Install', 'Makefile')
        SHUTILS_BIN = os.path.join(JKROOT_DIR, 'bin/shutils')
        if os.path.exists(JAKA_UPGRADE_MKFILE_PATH):
            # 需要提前确保/usr/etc/jkzuc/bin/shutils已经安装
            # 移交控制权到包内的makefile脚本
            # os.execl 不会返回，使用bash -c 替换当前进程，保留pid
            logger.debug(f'bash -c "cd {JAKA_UPGRADE_MKFILE_DIR} && {SHUTILS_BIN} install"')
            os.execl('/bin/bash', 'bash', '-c', f'cd {JAKA_UPGRADE_MKFILE_DIR} && {SHUTILS_BIN} install >> {_JKZUC_UPGRADE_LOG_PATH} 2>&1')
    
    logger.warn('no valid installation package directory could be found.')
    shutil.rmtree(_INSTALL_PATH, ignore_errors=True)
    return RetCode.RET_FAIL


if __name__ == "__main__":
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    file_handler = logging.FileHandler(_JKZUC_UPGRADE_LOG_PATH)
    file_handler.setLevel(logging.DEBUG)

    # 创建日志格式器
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    file_handler.setFormatter(formatter)

    # 将文件处理器添加到日志记录器
    logger.addHandler(file_handler)

    # stream_handler = logging.StreamHandler()
    # logger.addHandler(stream_handler)

    run_upgrade_loader()
